package com.emm.yixun.marketing.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.activiti.engine.HistoryService;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.NodeUserService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.ReserveAreaService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.ReserveArea;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.DictionaryDto;
import com.emm.yixun.common.model.dto.NoticeDto;
import com.emm.yixun.common.model.dto.ProjectSettingDto;
import com.emm.yixun.common.model.dto.ReserveAreaDto;
import com.emm.yixun.common.model.dto.ReseveAreaView;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.marketing.service.ReserveAreaServiceFacade;

@Service("reserveAreaServiceFacade")
@WebService(name = "com.emm.yixun.marketing.service.ReserveAreaServiceFacade")
public class ReserveAreaServiceFacadeImpl implements ReserveAreaServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ReserveAreaService service;

	@Autowired
	private SignedService signedService;

	@Autowired
	private ProjectRoomService projectRoomService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private UserService userService;

	@Autowired
	private ProjectSettingService projectSettingService;

	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private HistoryService historyService;

	@Autowired
	private NodeUserService nodeUserService;

	@Override
	public Response<ReserveAreaDto> save(ReserveAreaDto dto) {
		Signed signed = signedService.selectById(dto.getSignedId());
		Response<ReserveAreaDto> response = new Response<ReserveAreaDto>();
		try {
			dto.setAccessCode(signed.getProjectCode());
			ReserveAreaDto areaDto = new ReserveAreaDto();
			areaDto.setSignedId(dto.getSignedId());
			List<ReserveArea> reserveArea = service.selectListByDto(areaDto);
			if (reserveArea.size() == 0) {
				ReserveAreaDto mDto = service.create(dto);
				response.success(mDto);
			} else {
				for (ReserveArea areaObj : reserveArea) {
					if (areaObj.getAuditStatus().equals("1")) {
						response.setSuccess(false);
						response.setEntity(null);
						response.setResultMessage("信息已经审批成功");
						return response;
					} else if (areaObj.getAuditStatus().equals("0")) {
						response.setSuccess(false);
						response.setEntity(null);
						response.setResultMessage("信息已经提交");
						return response;
					} else {
						ReserveAreaDto mDto = service.create(dto);
						response.success(mDto);
						return response;
					}
				}

			}

		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(ReserveAreaDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			ReserveAreaDto mDto = new ReserveAreaDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<ReserveArea> findById(Long id) {
		Response<ReserveArea> response = new Response<ReserveArea>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			ReserveArea entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<ReserveArea> findByDto(ReserveAreaDto dto) {
		ResponseList<ReserveArea> response = new ResponseList<ReserveArea>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<ReserveArea> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<ReserveArea> findPageByDto(ReserveAreaDto dto, Integer begin, Integer row) {
		Page<ReserveArea> response = new Page<ReserveArea>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<ReserveArea> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ReseveAreaView reserveAreaFrom(Long sigId) {
		try {
			ReseveAreaView res = converView(sigId);
			return res;
		} catch (Exception e) {
			logger.error("reserveAreaFrom error: ", e);
		}
		return null;
	}

	public ReseveAreaView converView(Long sigId) {
		// 签约信息
		ReseveAreaView res = new ReseveAreaView();
		Signed signed = signedService.selectById(sigId);
		res = BeanUtil.convert2T(res, signed);
		// 房间信息
		ProjectRoom projectRoom = projectRoomService.selectById(signed.getRoomId());
		res = BeanUtil.convert2T(res, projectRoom);
		// 客户信息
		Customer customer = customerService.selectById(signed.getCustomerId());
		if (customer != null) {
			res = BeanUtil.convert2T(res, customer);
		}

		ReserveAreaDto dto = new ReserveAreaDto();
		dto.setSignedId(sigId);
		dto.setOrders("create_time desc");
		List<ReserveArea> reseveList = service.selectListByDto(dto);
		if (null != reseveList && reseveList.size() > 0) {
			ReserveArea reseve = reseveList.get(0);
			User user = userService.selectById(reseve.getCreateUserId());
			res.setUserName(user.getUserName());
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			res.setManageDate(df.format(reseve.getCreateTime()));
			res.setMeasuredArea(reseve.getMeasuredArea());
			res.setRemark(reseve.getRemark());
			res.setReceivableDate(reseve.getReceivableDate());
			res.setTrusteesDate(reseve.getTrusteesDate());
			res = BeanUtil.convert2T(res, reseve);
		} else {
			res.setAuditStatus("2");
		}

		return res;
	}

	@Override
	public ReseveAreaView reserveAreaDetail(Long id) {
		try {
			ReserveArea reserveArea = service.selectById(id);
			// 操作人
			User user = userService.selectById(reserveArea.getCreateUserId());

			ReseveAreaView res = converView(reserveArea.getSignedId());
			res.setUserName(user.getUserName());
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			res.setManageDate(df.format(reserveArea.getCreateTime()));
			res = BeanUtil.convert2T(res, reserveArea);
			return res;
		} catch (Exception e) {
			logger.error("reserveAreaDetail error: ", e);
		}
		return null;
	}

	/**
	 * 创建面积补差提醒消息
	 */
	@Override
	public CommonResDTO addNotice_MJBC(ReserveAreaDto reserveAreaDto, Map<String, Object> managerMap,
			String procInstId) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			// 操作人
			String operateUser = "";
			if (null != reserveAreaDto.getCreateUserId()) {
				User user = userService.selectById(reserveAreaDto.getCreateUserId());
				if (user != null) {
					operateUser = user.getUserName();
				}
			} else {
				logger.info("创建面积补差消息失败,操作人不存在! 面积补差Id = " + reserveAreaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("创建面积补差消息失败,操作人不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 房间名称
			Long roomId = null;
			String roomName = "";
			String projectCode = "";
			String projectName = "";
			Signed signed = null;
			if (null != reserveAreaDto.getSignedId()) {
				signed = signedService.selectById(reserveAreaDto.getSignedId());
				if (null != signed) {
					Project project = projectService.selectById(signed.getProjectId());
					if (null != project) {
						projectCode = project.getProjectCode();
						projectName = project.getProjectName();
					}
					ProjectRoom projectRoom = projectRoomService.selectById(signed.getRoomId());
					if (null != projectRoom) {
						roomId = projectRoom.getId();
						roomName = projectRoom.getCombinedName();
					} else {
						logger.info("创建面积补差消息失败,房源不存在! 面积补差Id = " + reserveAreaDto.getId());
						resDto.setErrorCode("00000");
						resDto.setErrorMsg("创建面积补差消息失败,房源不存在!");
						resDto.setResult("0");
						return resDto;
					}
				}
			} else {
				logger.info("创建面积补差消息失败,签约信息不存在! 面积补差Id = " + reserveAreaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("创建面积补差消息失败,签约信息不存在!");
				resDto.setResult("0");
				return resDto;
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(projectCode);
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
					.createProcessInstanceHistoryLogQuery(procInstId).singleResult();
			userList = nodeUserService.selectProcUserList(reserveAreaDto.getMerchantId(), null,
					processInstanceHistoryLog.getProcessDefinitionId(), null);
			if (userList.size() == 0) {
				logger.info("创建面积补差消息失败,待发送客户不存在! 面积补差Id = " + reserveAreaDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("创建面积补差消息失败,待发送客户不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 无房认筹, 获取字典表dictionary_value = 'NT19' 的消息模板
			// 消息模板: 面积补差审批申请。房号：${roomName}；操作人：${agent}
			String msgTemp = "面积补差审批申请。房号：${roomName}；操作人：${agent}";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT19");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null) {
				msgTemp = dic.getDictionaryName();
			}
			sendMsg = msgTemp.replace("${roomName}", roomName).replace("${agent}", operateUser);
			// 创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "182");
			noticeParamMap.put("noticeTempType", "NT19");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "面积补差审批申请");
			noticeParamMap.put("merchantId", String.valueOf(reserveAreaDto.getMerchantId()));
			noticeParamMap.put("projectCode", signed.getProjectCode());
			noticeParamMap.put("userCode", reserveAreaDto.getUserCode());
			noticeParamMap.put("accessCode", reserveAreaDto.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(reserveAreaDto.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 */
			Map<String, String> replaceValuesMap = new HashMap<String, String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, roomId == null ? "" : String.valueOf(roomId));
			replaceValuesMap.put(MsgUtil.ROOM_NAME, roomName);
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, "");
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, "");
			noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			/*
			 * (ym) 提醒内容增加超链接 end
			 */
			NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);

			// 推送消息待处理......
			resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "面积补差审批申请");
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("面积补差审批申请消息失败!");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}

	@Override
	public Response<Integer> importSave(ReserveAreaDto dto) {
		Response<Integer> response = new Response<Integer>();
		try {
			ReserveAreaDto res = service.create(dto);
			if (res != null) {
				response.success(1);
			} else {
				response.fail("90001", "新增数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updatebySignedId(ReserveAreaDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getSignedId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.updatebySignedId(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}
}
